// tests/sqlx_test.rs
use sqlx::{MySqlPool, Row};
use tokio;
use dotenvy::dotenv;
use std::env;

#[tokio::test]
async fn test_database_connection() {
    // 创建测试数据库连接池
    let pool = setup_test_pool().await;

    // 测试连接是否成功
    let result = sqlx::query("SELECT 1 as connected")
        .fetch_one(&pool)
        .await
        .expect("数据库连接失败");

    let connected: i32 = result.get("connected");
    assert_eq!(connected, 1);
}

async fn setup_test_pool() -> MySqlPool {
    // 加载 .env 文件
    dotenv().ok();

    // 从环境变量读取数据库配置
    let host = env::var("MYSQL_HOST").unwrap_or_else(|_| "127.0.0.1".to_string());
    let port = env::var("MYSQL_PORT").unwrap_or_else(|_| "3306".to_string());
    let user = env::var("MYSQL_USER").expect("MYSQL_USER must be set");
    let password = env::var("MYSQL_PASSWORD").expect("MYSQL_PASSWORD must be set");
    let database = env::var("MYSQL_DATABASE").expect("MYSQL_DATABASE must be set");
    println!("数据库连接URL: {}:{}@{}:{}/{}", user, password, host, port, database);
    // 构建数据库连接URL
    let database_url = format!(
        "mysql://{}:{}@{}:{}/{}",
        user, password, host, port, database
    );

    MySqlPool::connect(&database_url.as_str())
        .await
        .expect("无法创建数据库连接池")

}
